#include "include/muduo/net/TcpConnection.h"
#include "include/muduo/net/TcpClient.h"
#include "include/muduo/net/EventLoopThread.h"
#include "include/muduo/base/CountDownLatch.h"

#include <iostream>
#include <string>
#include <functional>

class TranslateClient
{
public:
    TranslateClient(const std::string &ip, int port)
        : _client(_baseloop.startLoop(), muduo::net::InetAddress(ip, port), "翻译服务器"), _latch(1)
    {
        _client.setConnectionCallback(std::bind(&TranslateClient::onConnection, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&TranslateClient::onMessage, this,
                                             std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }
    // 连接服务器
    void connect()
    {
        _client.connect(); // 与服务器建立连接
        _latch.wait();     // 在这里阻塞，直到建立连接成功
    }
    bool send(const std::string &msg)
    {
        // muduo中的操作都是异步的，需要判断连接是否任然存在
        if (_conn->connected())
        {
            _conn->send(msg);
            return true;
        }
        return false;
    }

private:
    // 新连接建立成功的回调函数
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected())
        {
            _latch.countDown(); // 唤醒阻塞的主线程
            _conn = conn;
        }
        else
        {
            // 重置连接
            _conn.reset();
        }
    }
    // 收到消息时的回调函数
    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp)
    {
        std::cout << "翻译结果为:" << buf->retrieveAllAsString() << std::endl;
    }

private:
    muduo::net::EventLoopThread _baseloop;
    muduo::net::TcpConnectionPtr _conn;
    muduo::net::TcpClient _client;
    muduo::CountDownLatch _latch;
};

int main()
{
    TranslateClient client("127.0.0.1", 8085);
    client.connect();

    while (1)
    {
        std::string buffer;
        std::cin >> buffer;
        if (!client.send(buffer))
            break;
    }
    return 0;
}